package com.web.webstart.base.util.jpa;

import com.alibaba.fastjson.JSON;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.entity.XaCmsUser;
import com.web.webstart.base.util.XaUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @ClassName: WebUitl
 * @Description: Web处理常用方法
 * @author eason.zt
 * @date 2014年2月24日 上午17:00:06
 * 
 */

public class WebUitl {
	
	
	private static String SORT_ASC="ASC";
	@SuppressWarnings("unused")
	private static String SORT_DESC="DESC";
	/**
	 * 构造分页参数（排序）.
	 * 
	 * @param pageNumber
	 *            the page number
	 * @param sort
	 *            the sort
	 * @return the page request
	 */
	public static PageRequest buildPageRequest(int pageNumber, String sort) {
		List<Sort.Order> orders = new ArrayList<Sort.Order>();
		if (XaUtil.isNotEmpty(sort)) {
			PageSort[] pageSorts = JSON.parseObject(sort, PageSort[].class);
			for (PageSort pageSort : pageSorts) {
				orders.add(new Order(Sort.Direction.valueOf(pageSort
						.getDirection()), pageSort.getProperty()));
			}
			Sort sorts = new Sort(orders);
			return new PageRequest(pageNumber - 1, 1, sorts);
		} else {
			return new PageRequest(pageNumber - 1, 1);
		}
	}

	/**
	 *
	 * @param pageNumber pago页
	 * @param pageSize 页面大小(默认为10条)
	 * @param sort 排序字段 可以是  [{property:'createTime',direction:'DESC'}]
	 * @return
	 */
	public static PageRequest buildPageRequest(int pageNumber, int pageSize,
			String sort) {

		List<Sort.Order> orders = new ArrayList<Sort.Order>();
		if (XaUtil.isEmpty(pageSize)) {
			pageSize = 10;
		}
		if (XaUtil.isNotEmpty(sort)) {
			PageSort[] pageSorts = JSON.parseObject(sort, PageSort[].class);
			for (PageSort pageSort : pageSorts) {
				if(SORT_ASC.equalsIgnoreCase(pageSort.getDirection())){
					orders.add(new Order(Sort.Direction.ASC, pageSort.getProperty()));
				}else{
					orders.add(new Order(Sort.Direction.DESC, pageSort.getProperty()));
				}
			}
			Sort sorts = new Sort(orders);
			return new PageRequest(pageNumber , pageSize, sorts);
		} else {
			return new PageRequest(pageNumber , pageSize);
		}
	}

	/**
	 * 取得带相同前缀的Request Parameters, copy from spring WebUtils.
	 * 没有条件: Map<String , Object> filterParams =  WebUitl.getParametersStartingWith("{}", "search_");
	 * 一个条件: Map<String, Object> filterParams   = WebUitl.getParametersStartingWith("{'search_EQ_userId':'" + userId + "'}", "search_");
	 * 2个以及以上个条件:
     * @<code>Map<String, Object> filterParams = WebUitl.getParametersStartingWith(
    "{'search_EQ_vSDC_Id':'"+ JConstant.VSDCStates.PASS+"'" +
    ",'search_NE_status':'"+ XaConstant.Status.delete+"'" +
    ",'search_EQ_userId':'"+userId+"'}", "search_");</code>
	 *
	 *  WebUitl.getParametersStartingWith("{'search_IN_id':'" + JSON.toJSONString(shopIdSetXr.getObject()) + "'}", "search_");
	 *
	 * 返回的结果的Parameter名已去除前缀.
	 *
	 * 说明:用json转换已经可以防止注入'这种特殊字符
	 *
	 *  Map数据：
	 *  key:EQ_userId
	 *  value:888
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getParametersStartingWith(
			String jsonFilter, String prefix) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		if (XaUtil.isNotEmpty(jsonFilter) && XaUtil.isNotEmpty(prefix)) {
			Map<String, String> map = JSON.parseObject(jsonFilter,
					HashMap.class);
			for (String key : map.keySet()) {
				if (key.startsWith(prefix)) {
					String unprefixed = key.substring(prefix.length());
					String value = map.get(key);
					searchParams.put(unprefixed, value);
				}
			}
		}
		return searchParams;
	}
	
	public static Long getCmsLoginedUserId(HttpServletRequest request){
		HttpSession session = request.getSession();
		XaCmsUser user = (XaCmsUser) session.getAttribute(XaConstant.SessionKey.currentUser);
		if(XaUtil.isNotEmpty(user)){
			return user.getUserId();
		}
		return 0L;
	}

	public static void main(String[] args) {
	}
}
